package com.mspbots.sync.wise.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.mspbots.sync.BaseGenericService;
import com.mspbots.sync.model.ExceptionLog;
import com.mspbots.sync.utils.WiseParamsUtils;
import com.mspbots.sync.wise.client.ClientProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * SkillsService is com.mspbots.sync.wise.service
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/2/6
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class SkillsService extends BaseGenericService {

    public Mono<JsonNode> getSkills(Map<String, String> params) {
        Integer tenantId = Integer.parseInt(params.get("tenantId"));
        params.put("orderBy", "id desc");
        params.put("pageSize", "500");
        return this.onGetWiseProperties(tenantId)
                .flatMap(configuration -> cwWebClient.getRepository("/system/skills",
                        WiseParamsUtils.mapToMultiValueMapBuild(params))
                        .subscriberContext(ctx -> ctx.put("properties", configuration)));
    }

    public Flux<JsonNode> getSkills(ClientProperties configuration) {
        MultiValueMap<String, String> params = WiseParamsUtils.paginationBuild("1", null);
        return this.cwWebClient.fetch("/system/skills", params)
                .subscriberContext(ctx -> ctx.put("properties", configuration))
                .switchMap(jsonNode -> {
                    if (ObjectUtils.isEmpty(jsonNode.get("id"))) {
                        log.error("This tenant sync skills error.msg: {}", jsonNode);
                        this.messagingTemplate.convertAndSend("exception.log", ExceptionLog.builder()
                                .tenantId(configuration.getTenantId()).name("Connect wise")
                                .status(500).type("SYNC-WISE-SKILLS").msg("Connect wise sync skills entry error.")
                                .extend(jsonNode).build());
                        return Flux.empty();
                    }
                    return Flux.just(jsonNode);
                });

    }

}
